package it.sd.wdc.spider.htmlbrowser;

import it.sd.wdc.spider.bean.PostParameters;

import org.apache.log4j.Logger;

/**
 * La classe contiene i metodi necessari per scaricare le pagine HTML da un
 * server web, inoltre contiene alcuni metodi di servizio usati per preparare la
 * chiamata ai metodi di navigazione
 */
public class WebClient {

	private WebTcpClientSession httpClient = null;

	private boolean cache = false;

	private CacheBrowser cacheBrowser = null;

	private Logger logger = Logger.getLogger(this.getClass());

	public WebClient() throws Exception {
    	
//		cacheBrowser = CacheFatory.getInstance();
		cacheBrowser = null;
		this.cache = (cacheBrowser!=null);
		httpClient = WebTcpClientFactory.getInstance().newSession(); 
	}

	/*
	public void downloadPdf(String url, PostParameters postData, String fileName,
			String dir) throws WebClientException {

		String fullPdfPath = dir + File.separator + fileName;

		String fileCache = null;
		if (cache) {
			try {
				fileCache = cacheBrowser.getPage(url, postData.getPostAsString());
			} catch (Exception e) {
				throw new WebClientException("errore cache", e);
			}
		}

		if (fileCache != null) {
			File input = new File(fileCache);
			File output = new File(fullPdfPath);
			try {
				FileUtils.copyFile(input, output);
			} catch (Exception e) {
				throw new WebClientException("Errore evasione", e);
			}
			return;
		}

		byte[] pdfData = httpClient.getBinaryPage(url, postData);

		
		if (!compareByteArrays(pdfData, pdfPattern)) {
			throw new DownloadPDFException(
					"Il file scaricato non � in formato PDF");
		} else {
			File destination = new File(fullPdfPath);
			if (destination.getParentFile() != null
					&& !destination.getParentFile().exists()) {
				destination.getParentFile().mkdirs();
			}

			try {
				FileOutputStream os = new FileOutputStream(destination);
				os.write(pdfData);
				os.close();
			} catch (FileNotFoundException e) {
				throw new WebClientException(e.getMessage());
			} catch (IOException e) {
				throw new WebClientException(e.getMessage());
			}

			if (cache) {
				try {
					cacheBrowser.setPage(url, postData.getPostAsString(), fullPdfPath);
				} catch (Exception e) {
					throw new WebClientException("errore cache", e);
				}
			}

		}
	}
*/
	public String getPage(String host, String action, String method, PostParameters postData)
			throws WebClientException {

		if (logger.isDebugEnabled()) {
			logger.debug("*******************************");
			logger.debug("URL: " + host+ action + "  " + postData);
		}

		String strPageHTML = null;

		if (cache) {
			try {
				strPageHTML = cacheBrowser.getPage(host + action, postData.getPostAsString());
			} catch (Exception e) {
				throw new WebClientException("errore cache", e);
			}
		}

		if (strPageHTML != null) {
//			if (logger.isDebugEnabled()) {
//				logger.debug("cache: " + strPageHTML);
//			}
			return strPageHTML;
		}

		strPageHTML = httpClient.getPage(host, action, method, postData);
		
		if (cache) {
			try {
				cacheBrowser.setPage(host + action, postData.getPostAsString(), strPageHTML);
			} catch (Exception e) {
				throw new WebClientException("errore cache", e);
			}
		}

//		if (logger.isDebugEnabled()) {
//			logger.debug("page: " + strPageHTML);
//		}
		return strPageHTML;
	}


	private static byte[] pdfPattern = { '%', 'P', 'D', 'F' };

	public static final char[] defaultSubstChars = { ' ', '_', '�', 'a', '�',
			'e', '�', 'e', '�', 'o', '�', 'u', '�', 'i', };

	public boolean compareByteArrays(byte[] src, byte[] dst) {
		if (src.length < dst.length)
			return false;

		for (int t = 0; t < dst.length; t++) {
			if (src[t] != dst[t])
				return false;
		}

		return true;
	}

	public void close() {
		try {
			httpClient.close();
		} catch(Exception e) {
			
		}
	}
}
